//
// Created by chench on 2/9/21.
//

#include "triple_des.h"



int main() {
    char *str = "0123456789abcdef0123456789abcdef";
    printf("%s\r\n", str);
    char *key = "0123456789abcdef01234567";
    char *buf = malloc(strlen(str) + 8);
    triple_des_ecb_cipher(1, key, str, buf);
    printf("%d:%s\r\n", strlen(buf), buf);

}

/**
 *
 * @param den 解密:0|加密:1
 * @param key 密钥
 * @param str 明文
 * @param buf 密文
 * @return
 */
int triple_des_ecb_cipher(int den, char *key, char *str, char *buf) {
    //3DES密钥长度24不够需要补全填充0x00
    int key_len = strlen(key);
    int cipher_length = 24;
    char *cipher = malloc(cipher_length);
    memcpy(cipher, key, key_len);
    memset(cipher + key_len, 0x00, cipher_length - key_len);

    char *invert = malloc(8);//密钥置换
    memset(invert, 0x00, strlen(invert));//填充0x00

    DES_key_schedule ks1, ks2, ks3;
    memcpy(invert, cipher + 0, 8);
    DES_set_key_unchecked((const_DES_cblock *) invert, &ks1);
    memcpy(invert, cipher + 8, 8);
    DES_set_key_unchecked((const_DES_cblock *) invert, &ks2);
    memcpy(invert, cipher + 16, 8);
    DES_set_key_unchecked((const_DES_cblock *) invert, &ks3);



    //3DES加密数据长度必须是8的整数倍不够需要补全填充余数
    int str_len = strlen(str);
    int data_fill = 8 - str_len % 8;
    int data_size = str_len + data_fill;
    char *data = malloc(data_size);
    memcpy(data, str, str_len);
    memset(data + str_len, data_fill, data_fill);//填充余数

    int i;
    char *input = malloc(8);
    char *output = malloc(8);
    //buf = malloc(buf, data_size);//存储返回结果
    //8字节循环加密解密
    for (i = 0; i < data_size / 8; i++) {
        memset(input, 0x00, 8);
        memset(output, 0x00, 8);

        if (den) {//加密
            memcpy(input, data + 8 * i, 8);
            DES_ecb3_encrypt((const_DES_cblock *) input, (DES_cblock *) output,
                             &ks1, &ks2, &ks3, DES_ENCRYPT);
        } else {//解密
            memcpy(input + 8 * i, output, 8);
            DES_ecb3_encrypt((const_DES_cblock *) input, (DES_cblock *) output,
                             &ks1, &ks2, &ks3, DES_ENCRYPT);
        }
        memcpy(buf + 8 * i, output, 8);
    }
    buf[data_size + 1] = '\0';
    return 0;
}